# -*- encoding: utf-8 -*-
'''
Created on 2011-04-19

@author: quermit
'''
import logging

from PyQt4.QtCore import Qt
from PyQt4.QtCore import QTimer
from PyQt4.QtGui import QLabel


log = logging.getLogger(__name__)


class QuotesTable(object):

    def __init__(self, table, refresh=1000):
        self.__table = table
        self.__quotes = {}
        self.__dirty = []

        self.__timer = QTimer()
        self.__timer.setSingleShot(False)
        self.__timer.timeout.connect(self.refresh)
        self.__timer.start(refresh)

    def get_widget(self):
        return self.__table

    def update_quote(self, data):
        index = unicode(data["origin_index"])
        name = unicode(data["name"])
        value = "%.2f" % data["rating"]
        turnover = "%dk" % data["turnover"]
        change_pln = "%+.2f" % data["changePLN"]
        change_perc = "%+.2f" % data["changePercent"]

        if name not in self.__quotes:
            self.__quotes[name] = {
                    'index': index,
                    'name': name,
                    'value': None,
                    'turnover': None,
                    'change_pln': change_pln,
                    'change_perc': change_perc,
                    'table_idx': None,
                }

        quote = self.__quotes[name]

        self.__update_quote(quote, name, value, 'value')
        self.__update_quote(quote, name, turnover, 'turnover')
        self.__update_quote(quote, name, change_pln, 'change_pln')
        self.__update_quote(quote, name, change_perc, 'change_perc')

    def __update_quote(self, quote, quote_name, value, value_name):
        if quote[value_name] != value and quote_name not in self.__dirty:
            self.__dirty.append(quote_name)

        quote[value_name] = value

    def refresh(self):
        if len(self.__dirty) == 0:
            return

        log.debug("dirty quotes: %d/%d" % (len(self.__dirty), len(self.__quotes)))

        for name in self.__dirty:
            quote = self.__quotes[name]
            if quote['table_idx'] is None:
                quote['table_idx'] = self.__insert_row(quote['index'], name)
            self.__set_value(quote['table_idx'], quote['value'])
            self.__set_turnover(quote['table_idx'], quote['turnover'])
            self.__set_change(quote['table_idx'], quote['change_pln'], quote['change_perc'])
        self.__dirty = []

    def __set_value(self, idx, value):
        widget = self.__table.cellWidget(idx, 3)
        if widget.text() and value:
            old = float(widget.text())
            new = float(value)
            if new - old > 0:
                self.__fade(widget, '#7CE872', '#D4F5CE')  # green
            if new - old < 0:
                self.__fade(widget, '#E87272', '#F5CECE')  # red
        widget.setText(value)

    def __set_turnover(self, idx, turnover):
        widget = self.__table.cellWidget(idx, 2)
        widget.setText(turnover)

    def __set_change(self, idx, change_pln, change_perc):
        widget = self.__table.cellWidget(idx, 4)
        widget.setText("%s (%s%%)" % (change_pln, change_perc))

    def __insert_row(self, index, name):
        rows = self.__table.rowCount()
        self.__table.setRowCount(rows + 1)

        index_widget = QLabel(index, self.__table)
        self.__table.setCellWidget(rows, 0, index_widget)

        name_widget = QLabel(name, self.__table)
        self.__table.setCellWidget(rows, 1, name_widget)

        #TODO: refactor

        value_widget = QLabel(self.__table)
        value_widget.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.__table.setCellWidget(rows, 2, value_widget)

        to_widget = QLabel(self.__table)
        to_widget.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.__table.setCellWidget(rows, 3, to_widget)

        change_widget = QLabel(self.__table)
        change_widget.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.__table.setCellWidget(rows, 4, change_widget)

        return rows

    def __fade(self, item, color, color2=None):
        item.setStyleSheet("background-color: %s;" % color);
        if color2:
            QTimer.singleShot(2000, lambda: self.__fade(item, color2))
